﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Linq;

using OctoOS;
using OctoOS.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class __admin_category : OOSPage
{
	class PathInfo
	{
		[PathInfoMember(0)]
		internal long categoryID;

        [PathInfoMember(1, true)]
        internal long parentCategoryID;
	}


	PathInfo _pathInfo;
    Category[] _allCategories = null;
    Category[] _parentCategories = null;
    Category _currentCategory = null;
    Resource _resource = null;

	protected void Page_Init(object sender, EventArgs e)
	{
        _resource = DataSource.ClassifiedResources_Get(
            OOSRequest.Current.ResourceID);
        if (_resource.ExistsMasterResource)
        {
            throw new HttpException(404, "Page is not found");
        }
#warning admin

        //OOSRequest.Current.EnsureModerator();

		_pathInfo = EnablePathInfo<PathInfo>();

        Helper.Categories.UpdateCategoryCache();
        _allCategories = Helper.Categories.GetAllCategories();

        if (_pathInfo.categoryID == 0)
        {
            var parentCategories = Helper.Categories.GetPossibleParentCategories(_pathInfo.categoryID);

            ListItem item = new ListItem("No parent category", "0");
            ParentCategory.Items.Add(item);
            foreach (var cat in parentCategories)
            {
                item = new ListItem(cat.LevelName, cat.ID.ToString());
                if (cat.ID == _pathInfo.parentCategoryID)
                {
                    item.Selected = true;
                }
                ParentCategory.Items.Add(item);
            }
        }
        else
        {
            _currentCategory = Helper.Categories.GetCategory(_pathInfo.categoryID);
            _parentCategories = Helper.Categories.GetPossibleParentCategories(_pathInfo.categoryID);
            ListItem item = new ListItem("No parent category", "0");
            ParentCategory.Items.Add(item);

            foreach (var cat in _parentCategories)
            {
                item = new ListItem(cat.LevelName, cat.ID.ToString());
                item.Selected = cat.ID == _currentCategory.ParentCategoryID;
                ParentCategory.Items.Add(item);
            }

            // attributes
            Attribute prev = null;
            Attribute curr = null;
            Attribute next = null;

            var attributes = DataSource.ClassifiedAttributes_GetByCategory(
               _pathInfo.categoryID);
            if (attributes.Length > 0)
            {
                AttributesView.Visible = true;
                for (int i = 0; i < attributes.Length; i++)
                {
                    // setting attribute sequence
                    prev = curr;
                    curr = attributes[i];
                    if (i < attributes.Length - 1)
                    {
                        next = attributes[i + 1];
                    }
                    else
                    {
                        next = null;
                    }

                    FormRow formRow = new FormRow();
                    formRow.ID = curr.ID.ToString();
                    formRow.Label = curr.Title;
                    formRow.Required = curr.Required;
                    // edit, delete attribute
                    formRow.Controls.Add(GetRowContent(prev, curr, next));
                    AttributesView.Controls.Add(formRow);
                }
            }
        }

        
	}

    protected void Page_Load(object sender, EventArgs e)
    {
        if (_pathInfo.categoryID == 0)
        {
            PageTitle = "Add New Category";
        }
        else
        {
            PageTitle = "Edit Category";

            if (_currentCategory != null)
            {
                if (!IsPostBack)
                {
                    CategoryName.Text = _currentCategory.Name;
                    ImageURL.Text = _currentCategory.ImageUrl;
                    RedirectURL.Text = _currentCategory.RedirectUrl;
                    AdNameExample.Text = _currentCategory.AdNameExample;
                    ReadOnly.Checked = _currentCategory.ReadOnly;
                }
            }
            else
            {
                throw new HttpException(404, "The Page Is not Found");
            }
        }
        //add submit button at the bottom
        OctoOS.UI.Submit submit = new Submit();
        FormRow submitForm = new FormRow();
        submit.ID = "submit";
        submit.Click += new EventHandler(OnSubmitClick);
        submitForm.Controls.Add(submit);
        FormView.Controls.Add(submitForm);

        SetBreadcrumbsAndActions();
    }

    private Control GetRowContent(Attribute prev, Attribute curr, Attribute next)
    {
        HtmlTable table = new HtmlTable();
        var tableRow = new HtmlTableRow();
        table.Style.Add("margin-left", "-0px");
        table.Style.Add("border-spacing", "0");


        var tableCellInput = new HtmlTableCell();
        tableCellInput.Style.Add("width", "100%");
        tableCellInput.Style.Add("padding", "0 8px 0 0");

        OctoOS.UI.Literal lit = new OctoOS.UI.Literal();
        foreach (var val in curr.AttributeValues)
        {
            if (!String.IsNullOrEmpty(lit.Text))
            {
                lit.Text += ", ";
            }
            lit.Text += val.AttributeValueName;
        }
        tableCellInput.Controls.Add(lit);

        var tableCellButtons = new HtmlTableCell();
        tableCellButtons.Controls.Add(GetCellButtons(prev, curr, next));

        tableRow.Cells.Add(tableCellInput);
        tableRow.Cells.Add(tableCellButtons);
        table.Rows.Add(tableRow);
        return table;
    }

    private Control GetCellButtons(Attribute prev, Attribute curr, Attribute next)
    {
        var linkButton = new OctoOS.UI.LinkButton();
        linkButton.Icon = "oosres://themes/images/kde/16/edit.png";

        var menu = new OctoOS.UI.Menu();
        if (prev != null)
        {
            menu.Controls.Add(new MenuButton("Move Up", "javascript:Attributes_ChangeOrder('" + _pathInfo.categoryID + "'," + curr.ID + "," + prev.ID + ")", ""));
        }
        if (next != null)
        {
            menu.Controls.Add(new MenuButton("Move Down", "javascript:Attributes_ChangeOrder('" +_pathInfo.categoryID +"'," + curr.ID + "," + next.ID + ")", ""));
        }
        menu.Controls.Add(new MenuSeparator());

        if (curr.IsCustom)
        {
            menu.Controls.Add(new MenuButton("Edit Attribute", Urls.Classifieds.GetCustomAttribute(_pathInfo.categoryID, curr.ID), ""));
            menu.Controls.Add(new MenuButton("Delete Attribute", Urls.Classifieds.GetAttributeDelete(_pathInfo.categoryID, curr.ID), ""));
        }
        else
        {
            menu.Controls.Add(new MenuButton("Edit Attribute", Urls.Classifieds.GetAttribute(_pathInfo.categoryID, curr.ID), ""));
            menu.Controls.Add(new MenuButton("Delete Attribute", Urls.Classifieds.GetAttributeDelete(_pathInfo.categoryID, curr.ID), ""));
        }
        linkButton.Controls.Add(menu);
        return linkButton;
    }



   private void SetBreadcrumbsAndActions()
   {
       Category parentCategory = Helper.Categories.GetParentCategory(_pathInfo.categoryID);
       Category grandParentCategory = Helper.Categories.GetGrandParentCategory(_pathInfo.categoryID);

       // breadcrumbs
       AddBreadcrumb(string.Empty, "/");
       AddBreadcrumb("Admin page", Urls.Classifieds.GetAdminDefault());
       if (grandParentCategory != null)
       {
           AddBreadcrumb(grandParentCategory.Name, Urls.Classifieds.GetCategoryEdit(grandParentCategory.ID));
       }
       if (parentCategory != null)
       {
           AddBreadcrumb(parentCategory.Name, Urls.Classifieds.GetCategoryEdit(parentCategory.ID));
       }

       // actions
       if (_pathInfo.categoryID != 0)
       {
           if (grandParentCategory == null)
           {
               AddAction("Add New Child Category", Urls.Classifieds.GetCategoryEdit(0, _currentCategory.ID));
           }
           AddAction("Delete Category", Urls.Classifieds.GetCategoryDelete(_pathInfo.categoryID));
           if (!_currentCategory.ReadOnly)
           {
               AddAction("Add Attribute", Urls.Classifieds.GetAttribute(_pathInfo.categoryID, 0));
               AddAction("Add Custom Attribute", Urls.Classifieds.GetCustomAttribute(_pathInfo.categoryID, 0));
           }
       }
   }

   protected void OnSubmitClick(object sender, EventArgs e)
   {
       if (Page.IsValid)
       {
            DataSource.ClassifiedCategories_Save(
                    OOSRequest.Current.ResourceID,
                    _pathInfo.categoryID == 0 ? OOSRequest.Current.RequestID : _pathInfo.categoryID,
                    Convert.ToInt64(ParentCategory.SelectedValue),
                    CategoryName.TrimmedText,
                    AdNameExample.TrimmedText,
                    ImageURL.TrimmedText,
                    RedirectURL.TrimmedText,
                    ReadOnly.Checked);

            Response.Redirect(Urls.Classifieds.GetCategoryEdit(_pathInfo.categoryID == 0 ? OOSRequest.Current.RequestID : _pathInfo.categoryID));
       }
   }

   // shouldnt exist 2 same names at the same level
   protected void NameValidate(object sender, ValidateEventArgs e)
   {
       foreach (var cat in _allCategories)
       {
           
           if (cat.Name == CategoryName.TrimmedText
               && cat.ParentCategoryID == Convert.ToInt64(ParentCategory.SelectedValue)
               && (_currentCategory == null? 0 :_currentCategory.ID) != cat.ID)
           {
               e.ErrorMessage = "Category with this name already exists at this level";
               break;
           }
       }
   }
}